package com.ssyc.student.activity;

import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UIHelper;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyGridView;
import com.ssyc.common.view.ZzHorizontalProgressBar;
import com.ssyc.common.view.vp.SuperViewPager;
import com.ssyc.student.R;
import com.ssyc.student.adapter.ClassGvAdapter;
import com.ssyc.student.bean.ClassInfo;
import com.ssyc.student.bean.ErrorQuestionsListInfo;
import com.ssyc.student.fragment.StudentErrorConjunctionsFragment;
import com.ssyc.student.fragment.StudentErrorSingleChooseFragment;
import com.ssyc.student.fragment.StudentErrorTranslateFragment;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 教师端--金牌金概念2--题型选择--语法错题界面
 * Created by Kevin on 2018/5/29
 */

public class ErrorQuestionsListActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {

    //返回按钮
    private ImageView ivBack;

    //底部的ViewPager
    private SuperViewPager vp;

    //底部的显示Vp页数的文本
    private TextView tvPos;

    //选择班级
//    private TextView tv_choice_class;


    //填充ViewPager的Fragment集合
    private List<Fragment> mFragments;

    //ViewPager的适配器
    private VpCommonAdapter adapter;

    //记录当前ViewPager滑动的位置
    private int pos = 0;

    //Handler对象
    private Handler handler = new Handler();

    //进度条
    private ZzHorizontalProgressBar pb;

    //获取LessonId的key
    public static final String LESSONID = "lessonid";

    //获取GradeId的key
    public static final String GRADEID = "gradeid";

    //LessonId
    private String lessonId;

    private String classNum;



    private ErrorQuestionsListInfo errorInfo;

    //移除题目后刷新数据
    public static final String DELREFLASH = "delreflash";

    //标题栏的布局
    private LinearLayout llTitle;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //是否获取班级列表数据完成的标识,没完成之前点击选择班级的弹框提示正在加载,不允许点击
    private boolean isLoadClassCompleted;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.activity_error_questions_list;
    }

    @Override
    protected void init() {

        //初始化View
        initView();

        //获取传递过来的对象
        initIntent();

        //请求服务器
        http();
    }


    /**
     * 初始化控件
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        tvPos = findViewById(R.id.tv_vp_pos);
        vp.addOnPageChangeListener(this);
        pb = findViewById(R.id.pb);
        //标题栏
        llTitle = findViewById(R.id.ll_title);
//        tv_choice_class = findViewById(R.id.tv_choice_class);
//        tv_choice_class.setOnClickListener(this);
    }

    /**
     * 获取传递过来的对象
     */
    private void initIntent() {
        lessonId = getIntent().getStringExtra(LESSONID);
//      gradeId = getIntent().getStringExtra(GRADEID);
        classNum = getIntent().getStringExtra("num");
        Log.i("test",classNum);
    }


    /**
     * 请求服务器
     */
    private void http() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "32");
        map.put("acc", AccountUtils.getAccount(this));
        map.put("lessonId", lessonId);
        map.put("classNum", classNum);
        map.put("role", AccountUtils.getRole(this));
        map.put("apptoken", AccountUtils.getToken(this));
//        map.put("acc", "15608630008");
//        map.put("lessonId", "1");
//        map.put("role","0");
//        map.put("apptoken", "WHBHWJDSAKDAKSDNSAJDAK");
        map.put("platform", "8");

        HttpUtils.post(HttpAdress.ERRORQUESTIONS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                ErrorQuestionsListInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ErrorQuestionsListInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
                Log.i("test", "错题集：" + response);
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        //初始化Fragments
                        initFragments(info);

                        //初始化Vp的操作
                        initVp();

                        errorInfo = info;

                        BusInfo busInfo = new BusInfo();
                            busInfo.setType(NewConceptTwoActivity.UPDATE);
                            EventBus.getDefault().post(busInfo);
                    } else {
                        Log.i("test", info.getState() + "");
                    }
                }
            }
        });
    }


    /**
     * 初始化Fragments的方法,需要在请求服务器后获取到数据后执行
     */
    private void initFragments(ErrorQuestionsListInfo info) {
        mFragments = new ArrayList<>();
        //判断错题集非空
        if(info.getData().getError_list()!=null&&info.getData().getError_list().size()!=0){

        for (int i = 0; i < info.getData().getError_list().size(); i++) {
            if ("29".equals(info.getData().getError_list().get(i).getType())) {
                //连词成句
                mFragments.add(StudentErrorConjunctionsFragment.newInstance(
                        GsonUtil.objectToJson(info.getData()), i));
            } else if ("30".equals(info.getData().getError_list().get(i).getType())) {
                //翻译
                mFragments.add(StudentErrorTranslateFragment.newInstance(
                        GsonUtil.objectToJson(info.getData()), i));
            } else if ("31".equals(info.getData().getError_list().get(i).getType())) {
                //单选
                mFragments.add(StudentErrorSingleChooseFragment.newInstance(
                        GsonUtil.objectToJson(info.getData()), i));
            }
        }

        //添加最后一个提交页面的Fragment
//      mFragments.add(StudentGrammarCommitFragment.newInstance(GsonUtil.objectToJson(info), lessonId, gradeId,energy));

        //设置当前展示的Vp的页码
        tvPos.setText("1/" + (mFragments.size()));

        //设置默认进度条的值
        pb.setProgress((int) ((float) (1) / (float) (mFragments.size()) * 100));
        }else{
            UIHelper.showToast(this,"目前没有产生错题");
        }
    }


    /**
     * 设置ViewPager的方法
     */
    private void initVp() {
        adapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(mFragments.size());
    }

    /**
     * ViewPager的滚动监听
     *
     * @param position
     * @param positionOffset
     * @param positionOffsetPixels
     */
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        pos = position;
//        if (position != mFragments.size() - 1) {
//            tvPos.setVisibility(View.VISIBLE);
//            tvPos.setText((position + 1) + "/" + (mFragments.size() - 1));
//        } else {
//            tvPos.setVisibility(View.GONE);
//        }
//        //记录当前滑动位置
//        currPos = position;
//        //复制vp滑动的最大位置值
//        if (position > maxPos) {
//            maxPos = position;
//        }
//        //根据当前位置来设置Vp是否可以向右滑动
//        if (currPos < maxPos) {
//            //如果当前位置小于Vp滑动过的最大位置,则可以右滑,否则不能右滑
//            vp.setScrollble(true);
//        } else {
//            vp.setScrollble(false);
//        }

        //最后一个位置不进行设置
        if (position != mFragments.size()) {
            //设置进度条的文本显示值
            tvPos.setText((position + 1) + "/" + (mFragments.size()));

            //同时需要设置进度条的值
            pb.setProgress((int) ((float) (pos + 1) / (float) (mFragments.size()) * 100));
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    /**
     * 接受事件的方法
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && DELREFLASH.equals(busInfo.msg)) {

            if (busInfo.getPos() < mFragments.size()) {
                //移除
                errorInfo.getData().getError_list().remove(busInfo.getPos());

                initFragments(errorInfo);

                if (errorInfo.getData().getError_list().size() == 0) {
                    UIHelper.showToast(this, "已移除所有错题");
                }
                initVp();
                if (busInfo.getPos() != 0) {
                    vp.setCurrentItem(busInfo.getPos() - 1);
                }
            }
        }
    }

    /**
     * 获取班级列表的数据
     */
    private void httpClass() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "5");
        map.put("c", AccountUtils.getAccount(this));
        map.put("user_type", AccountUtils.getUserType(this));
        map.put("platform", "8");
        HttpUtils.post(HttpAdress.GETCLASS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {
                ClassInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ClassInfo.class);
                } catch (Exception e) {
                    Log.i("test", "数据解析异常");
                }

                if (null != info) {
                    if ("1".equals(info.getStatus())) {
                        //返回成功
                        classInfos = info.getList();
                        if (null != classInfos && classInfos.size() != 0) {
                            //加载完班级列表数据后并且设置好列表展示数据后标题栏选择班级弹框可以进行点击了
                            isLoadClassCompleted = true;
                            //默认加载第一个班级的数据
                        } else {
                            UiUtils.Toast("没有班级数据", false);
                        }

                    } else {
                        //返回错误
                        UiUtils.Toast("服务器返回异常,状态码是:" + info.getStatus(), false);
                        Log.i("test", "服务器返回异常,状态码是:" + info.getStatus());
                    }

                } else {
                    Log.i("test", "服务器返回数据为空");
                }

            }
        });
    }

    /**
     * 页面控件的点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.iv_back) {
            //关闭
            finish();
        }
//        else if(id == R.id.tv_choice_class){
//            //选择班级
//            if (isLoadClassCompleted) {
//                //弹出选择班级的PopUpWindow
//                onChoiceClass();
//            } else {
//                //没加载完成
//                SnackbarUtil.ShortSnackbar(llBaseMain, "正在加载,不能选择班级", 0);
//            }
//        }
    }

    /**
     * 同步班级列表GridView的选中和没选中的状态
     */
    private void syncClassGvState() {
        for (int i = 0; i < classInfos.size(); i++) {
            if (popSelectedPos == i) {
                classInfos.get(i).setSelected(true);
            } else {
                classInfos.get(i).setSelected(false);
            }
        }
    }

    /**
     * 弹窗
     */
    private void onChoiceClass() {

        if (null == classInfos || classInfos.size() == 0) {
            //证明没有班级列表数据,不做任何操作
            return;
        } else {
            PopUpManager.showPop(this, R.layout.student_pop_class, 0.3f, llTitle, new PopUpManager.onGetViewListener() {
                @Override
                public void getChildView(View view, int layoutResId) {
                    //展示班级列表的GridView
                    MyGridView gv = view.findViewById(R.id.gv);


                    //第一步:设置默认的选中状态的班级位置
                    syncClassGvState();

                    //第二步:设置列表数据
                    classGvAdapter = new ClassGvAdapter(ErrorQuestionsListActivity.this,
                            classInfos, R.layout.student_gv_class);
                    gv.setAdapter(classGvAdapter);

                    //第三步:设置点击事件
                    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                            //记录选中的位置
                            popSelectedPos = pos;

                            //同步GridView的状态,设置列表的选中状态
                            syncClassGvState();

                            //通知适配器刷新
                            classGvAdapter.notifyDataSetChanged();

                            //根据当前选中的班级去请求班级小组的数据
//                            http(classInfos.get(pos).getClassnum());

                            //延迟关闭弹框
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    PopUpManager.dismiss();
                                }
                            }, 100);

                        }
                    });
                }
            });
        }
    }
}
